package com.sc.web.promotion;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.model.ParamMap;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.promotion.Promotion;
import com.sc.service.goods.GoodsService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;
import com.sc.web.BaseController;
import com.sc.web.annotation.SystemLog;
import com.sc.web.plugin.PageView;

//促销管理
@Controller
@RequestMapping(value="promotion")
public class PromotionController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private PromotionService promotionService;
	
	@Autowired
	private GoodsService goodsService;
	
	@RequestMapping("list")
	public String list(Model model,String pageNow, String pageSize, String column, String sort) throws Exception {
		model.addAttribute("res", findByRes());
		return "promotion/list";
	}
	
	//促销类型列表
	@RequestMapping("selectList")
	@ResponseBody
	public PageView promotionlist(Model model,String pageNow, String pageSize, String column, String sort) throws Exception {
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		try{
			//查询商品数据
			ParamMap paramMap = getFormMap(ParamMap.class);
			paramMap = toFormMap(paramMap, pageNow, pageSize,paramMap.getStr("orderby"));
			paramMap.put("column", column);
			paramMap.put("sort", sort);
			
			List<Promotion> goodsList = promotionService.selectList(paramMap);
			pageView.setRecords(goodsList);
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			logger.info("查询促销记录数据成功!");
		}catch(Exception e){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询促销记录数据异常:"+e);
			throw new ScBizException("查询促销记录数据异常！", e);
		}
		return pageView;
	}
	
	//添加促销类型
	@RequestMapping(value="add",method = RequestMethod.GET)
	public String add(Model model) throws Exception {
		return "promotion/add";
	}
	
	@RequestMapping(value="addEntity",method = RequestMethod.POST)
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销列表-新增促销")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity(Model model,HttpServletRequest request) throws Exception {
		Promotion promotion = new Promotion();
		String proTitle = request.getParameter("proTitle");
		String proType = request.getParameter("proType");
		String proStart = request.getParameter("proStart");
		String proEnd = request.getParameter("proEnd");
		promotion.setId(0);
		promotion.setProTitle(proTitle);
		promotion.setProType(proType);
		SimpleDateFormat stf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = stf.parse(proStart);
		Date end = stf.parse(proEnd);
		promotion.setProStart(start);
		promotion.setProEnd(end);
		try{
			promotionService.insert(promotion);
		}catch(Exception e){
			logger.error("促销类型数据保存异常！"+e);
			throw new ScBizException("促销类型数据保存异常！", e);
		}
		return "\"success\"";
	}
	
	//删除促销类型
	@RequestMapping("del")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销列表-删除促销")//凡需要处理业务逻辑的.都需要记录操作日志
	public String del(Model model,HttpServletRequest request) throws Exception {
		try{
			String id =getPara("ids");
			String[] ids = id.split(",");
			for(String i:ids){
				if(Common.isNotEmpty(i)){
				 int idInt = Integer.parseInt(i);
				 promotionService.deleteByPrimaryKey(idInt);
				}
			}
			return "\"success\"";
		}catch(Exception e){
			logger.error("促销类型数据保存异常！"+e);
			throw new ScBizException("促销类型数据保存异常！", e);
		}
	}
	
	//编辑促销类型
	@RequestMapping(value="edit",method = RequestMethod.GET)
	public String addEdit(Model model,Integer id) throws Exception {
		Promotion promotion =promotionService.selectByPrimaryKey(id);
		model.addAttribute("promotion", promotion);
		return "promotion/edit";
	}
	
	@RequestMapping(value="savePro",method = RequestMethod.POST)
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销列表-修改促销")//凡需要处理业务逻辑的.都需要记录操作日志
	public String savePro(Model model,HttpServletRequest request) throws Exception {
		Promotion promotion = new Promotion();
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		String proTitle = request.getParameter("proTitle");
		String proType = request.getParameter("proType");
		String proStart = request.getParameter("proStart");
		String proEnd = request.getParameter("proEnd");
		promotion.setId(id);
		promotion.setProTitle(proTitle);
		promotion.setProType(proType);
		SimpleDateFormat stf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = stf.parse(proStart);
		Date end = stf.parse(proEnd);
		promotion.setProStart(start);
		promotion.setProEnd(end);
		try{
			if(promotion.getId()==null){
				promotionService.insert(promotion);
			}else{
				promotionService.updateByPrimaryKeySelective(promotion);
			}
			
		}catch(Exception e){
			logger.error("促销类型数据保存异常！"+e);
			throw new ScBizException("促销类型数据保存异常！", e);
		}
		return "\"success\"";
	}

	/**
	 * @Title: listUI
	 * @Description 促销明细页面
	 * @date 2017年4月6日上午9:34:23
	 * @param model
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping("detail/list")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return "/promotion/detail/list";
	}
	/**
	 * @Title: findByPage
	 * @Description 促销明细列表
	 * @date 2017年4月6日上午9:40:23
	 * @param pageNow
	 * @param pageSize
	 * @param column
	 * @param sort
	 * @author LeiJia  
	 * @return PageView    返回类型
	 */
	@ResponseBody
	@RequestMapping("detail/selectList")
	public PageView findByPage( String pageNow,
			String pageSize,String column,String sort) throws Exception {
		//查询订单数据
		ParamMap paramMap = getFormMap(ParamMap.class);
		paramMap = toFormMap(paramMap, pageNow, pageSize,paramMap.getStr("orderby"));
		paramMap.put("column", column);
		paramMap.put("sort", sort);
		List<PromotionDetailDto> list = new ArrayList<PromotionDetailDto>();
		List<Map<String,Object>>  resultMap = promotionService.selectByParam(paramMap);
		if(resultMap != null && resultMap.size() >0){
			for(Map<String,Object> map :resultMap){
				PromotionDetailDto dto = new PromotionDetailDto();
				if(map.get("pro_detail_id") != null){
					dto.setId((Integer)map.get("pro_detail_id"));
					dto.setPro_detail_id((Integer)map.get("pro_detail_id"));
				}
				if(map.get("pro_id") != null)
					dto.setPro_id((Integer)map.get("pro_id"));
				if(map.get("pro_title") != null)
					dto.setPro_title(map.get("pro_title").toString());
				if(map.get("pro_type") != null)
					dto.setPro_type(map.get("pro_type").toString());
				if(map.get("pro_count") != null)
					dto.setPro_count(map.get("pro_count").toString());
				if(map.get("pro_goods") != null)
					dto.setPro_goods(map.get("pro_goods").toString());
				if(map.get("pro_start") != null)
					dto.setPro_start((Date)map.get("pro_start"));
				if(map.get("pro_end") != null)
					dto.setPro_end((Date)map.get("pro_end"));
				if(map.get("pro_money") != null)
					dto.setPro_money(map.get("pro_money").toString());
				if(map.get("pro_rate") != null)
					dto.setPro_rate(map.get("pro_rate").toString());
				if(map.get("ext") != null)
					dto.setExt(map.get("ext").toString());
				if(map.get("ext1") != null)
					dto.setExt1(map.get("ext1").toString());
				list.add(dto);
			}
		}
        pageView.setRecords(list);//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	
	/**
	 * @Title: addDetail
	 * @Description 添加促销明细页面
	 * @date 2017年4月6日下午 14:28:34
	 * @param model
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping(value="detail/add",method = RequestMethod.GET)
	public String addDetail(Model model) throws Exception {
		return "promotion/detail/add";
	}
	/**
	 * @Title: addEntityDetail
	 * @Description 添加促销明细
	 * @date 2017年4月6日下午 14:30:03
	 * @param model
	 * @param request
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@ResponseBody
	@RequestMapping(value="detail/addEntity",method = RequestMethod.POST)
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销详细列表-新增促销详细")//凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntityDetail(Model model,HttpServletRequest request, PromotionDetailDto dto) throws Exception {		
		try{
			String pro_type = dto.getPro_type();
			switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(dto.getPro_money_m()) && Common.isNotEmpty(dto.getPro_money_s())){					
					dto.setPro_money(dto.getPro_money_m() + ":" + dto.getPro_money_s());
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(dto.getPro_money_m_mj()) && Common.isNotEmpty(dto.getPro_money_s_mj())){					
					dto.setPro_money(dto.getPro_money_m_mj() + ":" + dto.getPro_money_s_mj());
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(dto.getPro_count_m()) && Common.isNotEmpty(dto.getPro_count_s())){					
					dto.setPro_count(dto.getPro_count_m() + ":" + dto.getPro_count_s());
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(dto.getPro_count_m_dz()) && Common.isNotEmpty(dto.getPro_rate())){					
					dto.setPro_count(dto.getPro_count_m_dz() );
				}
				break;
		  }			
		promotionService.insertPromotionDetail(dto);
		}catch(Exception e){
			logger.error("添加出校详细数据保存异常！"+e);
			throw new ScBizException("添加出校详细数据保存异常！", e);
		}
		return "\"success\"";
	}
	
	/**
	 * @Title: delDetail
	 * @Description 删除促销详细
	 * @date 2017年4月6日下午 14:32:43
	 * @param model
	 * @param request
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping("detail/del")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销详细列表-删除促销详细")//凡需要处理业务逻辑的.都需要记录操作日志
	public String delDetail(Model model,HttpServletRequest request) throws Exception {
		try{
			String id =getPara("ids");
			String[] ids = id.split(",");
			for(String i:ids){
				if(Common.isNotEmpty(i)){
					int idInt = Integer.parseInt(i);
					promotionService.deleteProDetailByPrimaryKey(idInt);
				}
			}
			return "\"success\"";
		}catch(Exception e){
			logger.error("删除促销详细异常！"+e);
			throw new ScBizException("删除促销详细异常！", e);
		}
	}
	
	/**
	 * @Title: addEditDetail
	 * @Description 修改促销明细
	 * @date 2017年4月6日下午 14:32:43
	 * @param model
	 * @param id
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping(value="detail/edit",method = RequestMethod.GET)
	public String addEditDetail(Model model,Integer id) throws Exception {
	    List<Goods> goodsList =new ArrayList<Goods>();    
		PromotionDetailDto promotionDetail =promotionService.selectProDetailByPrimaryKey(id);
		String pro_gooods = promotionDetail.getPro_goods();
		String[] goods_ids =null;
		if(Common.isNotEmpty(pro_gooods)){
			goods_ids =pro_gooods.split(",");
			for(String goods_id : goods_ids){
				Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(goods_id));
				goodsList.add(goods);
			}
		}
		String pro_type = promotionDetail.getPro_type();
		String pro_money = promotionDetail.getPro_money();
		String pro_count = promotionDetail.getPro_count();
		switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(pro_money)){
					promotionDetail.setPro_money_m(pro_money.split(":")[0]);
					promotionDetail.setPro_money_s(pro_money.split(":")[1]);
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(pro_money)){
					promotionDetail.setPro_money_m(pro_money.split(":")[0]);
					promotionDetail.setPro_money_s(pro_money.split(":")[1]);
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(pro_count)){
					promotionDetail.setPro_count_m(pro_count.split(":")[0]);
					promotionDetail.setPro_count_s(pro_count.split(":")[1]);
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(pro_count)){
					promotionDetail.setPro_count_m(pro_count);
				}
				break;
		}
		promotionDetail.setGoodsList(goodsList);
		model.addAttribute("promotionDetail", promotionDetail);
		return "promotion/detail/edit";
	}
	@RequestMapping(value="detail/updateProDetail",method = RequestMethod.POST)
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="促销管理",methods="促销详细列表-修改促销详细")//凡需要处理业务逻辑的.都需要记录操作日志
	public String updateProDetail(Model model,HttpServletRequest request,PromotionDetailDto dto) throws Exception {
		try{
			String pro_type = dto.getPro_type();
			switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(dto.getPro_money_m()) && Common.isNotEmpty(dto.getPro_money_s())){					
					dto.setPro_money(dto.getPro_money_m() + ":" + dto.getPro_money_s());
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(dto.getPro_money_m_mj()) && Common.isNotEmpty(dto.getPro_money_s_mj())){					
					dto.setPro_money(dto.getPro_money_m_mj() + ":" + dto.getPro_money_s_mj());
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(dto.getPro_count_m()) && Common.isNotEmpty(dto.getPro_count_s())){					
					dto.setPro_count(dto.getPro_count_m() + ":" + dto.getPro_count_s());
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(dto.getPro_count_m_dz()) && Common.isNotEmpty(dto.getPro_rate())){					
					dto.setPro_count(dto.getPro_count_m_dz() );
				}
				break;
		}
			promotionService.updateProDetail(dto);
		}catch(Exception e){
			logger.error("添加出校详细数据保存异常！"+e);
			throw new ScBizException("添加出校详细数据保存异常！", e);
		}
		return "\"success\"";
	}
	/**
	 * @Title: getProByType
	 * @Description 
	 * @date 2017年4月6日下午 14:32:43
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping("detail/getProByType")
	@ResponseBody
	public List<Promotion> getProByType(){
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		String pro_type = getPara("pro_type");
		paramMap.put("pro_type", pro_type);

		List<Promotion> list = null;
		try{
            list = promotionService.selectList(paramMap);
		}catch(Exception e){
			e.printStackTrace();
		}
		return list; 
	}
	
	
}
